﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Scheduler
{
    [DebuggerStepThrough]
    public class WorkerTaskScheduler : TaskScheduler, IDisposable
    {
        private readonly BlockingCollection<Task> _mQueue = new BlockingCollection<Task>();

        private readonly Thread _runThread;

        public WorkerTaskScheduler()
        {
            _runThread = new Thread(Run)
            {
                IsBackground = true,
                Priority = ThreadPriority.Highest
            };
            _runThread.Start();

        }
        [DebuggerStepThrough]
        private void Run()
        {
            Task t;
        
            while (_mQueue.TryTake(out t, Timeout.Infinite))
            {
                TryExecuteTask(t);
            }
        }
        protected override IEnumerable<Task> GetScheduledTasks()
        {
            return _mQueue;
        }
        protected override void QueueTask(Task task)
        {
            _mQueue.Add(task);
        }
        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            return false;
        }
        public void Dispose()
        {
            _runThread.Abort();
        }
    }
}

